<template>
  <div class="login_container">
    <div class="login_box">
      <div class="avatar_box">
        <img src="../assets/logo.svg" alt="">
      </div>
      <el-form ref="loginFormRef" class="login_form" :rules="loginFormRules" :model="form" label-width="0px">
        <el-form-item label="" prop="username">
          <el-input v-model="form.username" prefix-icon="iconfont"/>
        </el-form-item>
        <el-form-item label="" prop="password">
          <el-input v-model="form.password" type="password" prefix-icon="iconfont"/>
        </el-form-item>

        <el-form-item class="btns">
          <el-button type="primary" @click="login">登录</el-button>
          <el-button @click="resetLoginForm" type="info">重置</el-button>
        </el-form-item>
      </el-form>

    </div>
  </div>
</template>

<script>
  export default {
    name: 'Login',
    data () {
      return {
        form: {
          username: 'admin',
          password: '123456',
        },
        // 表单验证规则对象
        loginFormRules: {
          username: [
            { required: true, message: '登录名称', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在3到5之间', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入登录密码', trigger: 'blur' },
            { min: 3, max: 8, message: '长度在3到8之间', trigger: 'blur' }
          ],
        },
      }
    },
    methods: {
      // 表单的重置
      resetLoginForm() {
        this.$refs.loginFormRef.resetFields()
      },
      login() {
        // 表单验证结果 isValid boolean值验证是否通过
        this.$refs.loginFormRef.validate(async (isValid, invalidFields) => {
          if (!isValid) return
          let { data: res } = await this.$http.post('login', this.form)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success('登陆成功')
          // 将token存储到会话存储中，保证部分页面需要登录后才能访问
          window.sessionStorage.setItem("token", res.data.token)
          this.$router.push('/home')
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .login_container {
    background-color: #2b4b6b;
    height: 100%;
  }

  .login_box {
    width: 450px;
    height: 300px;
    background-color: #fff;
    border-radius: 3px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }

  .avatar_box {
    height: 130px;
    width: 130px;
    border-radius: 50%;
    border: 1px solid #eee;
    padding: 10px;
    background-color: #eee;
    box-shadow: 0 0 10px #eee;
    position: absolute;
    left: 50%;
    transform: translate(-50%, -50%);

    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
    }
  }

  .login_form {
    width: 100%;
    position: absolute;
    bottom: 0;
    padding: 0 20px;
    box-sizing: border-box;
  }

  .btns {
    display: flex;
    justify-content: flex-end;
  }

  .icon_login {
    position: absolute;
    top: 50%;
  }

</style>